package com.mico.examplet.springboot.webshell.config;

import com.mico.examplet.springboot.webshell.handler.Server;
import com.mico.examplet.springboot.webshell.handler.ShellClient;
import com.mico.examplet.springboot.webshell.handler.WebsocketUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/web_shell")
@Component
public class WebSocket {
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;



    //客户端
    ShellClient client = null;

    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        InetSocketAddress remoteAddress = WebsocketUtil.getRemoteAddress(session);
        System.out.println("有新连接加入！ip 为:"+remoteAddress.getAddress().getHostAddress()+",当前在线人数为" + webSocketSet.size());
        //做多个用户处理的时候，可以在这个地方来 ,判断用户id和
        //配置服务器信息
        Server server = new Server("115.159.221.201","root","MicoCube@0401");

        //初始化客户端
        client = new ShellClient(server, session);

        //连接服务器
        client.connect();
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        //关闭连接
        if (client != null) {
            System.out.println("有连接关闭，关闭其ssh连接");
            client.disconnect();
        }
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param msg 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String msg, Session session) {
        System.out.println("来自客户端的消息:" + msg);

        //处理连接
        try {
            //当客户端不为空的情况
            if (client != null) {
                //receive a close cmd ?
                if (Arrays.equals("exit".getBytes(), msg.getBytes())) {

                    if (client != null) {
                        client.disconnect();
                    }

                    session.close();
                    return ;
                }
                //写入前台传递过来的命令，发送到目标服务器上
                client.write(new String(msg.getBytes(), "UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                session.getBasicRemote().sendText("An error occured, websocket is closed.");
                session.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        for (WebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

}